package com.cykj.pos.util;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Security;

public class AESUtilApi {
    // add new bouncycastle ciphers
    static {
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    }

    /**
     * encrypt input text
     *
     * @param input
     * @param key
     * @return
     */
    public static String encrypt(String input, String key) {

        try {
            byte[] crypted = null;
            SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");

            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
            cipher.init(Cipher.ENCRYPT_MODE, skey);
            crypted = cipher.doFinal(input.getBytes());
            return new String(Base64.encodeBase64(crypted));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

    /**
     * decrypt input text
     *
     * @param input
     * @param key
     * @return
     */
    public static String decrypt(String input, String key) {

        try {
            byte[] output = null;
            SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
            cipher.init(Cipher.DECRYPT_MODE, skey);
            output = cipher.doFinal(Base64.decodeBase64(input));
            return new String(output);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

}
